from pyecharts import options as opts
from pyecharts.charts import Bar, Grid, Line, Liquid, Page, Pie
from pyecharts.commons.utils import JsCode
from pyecharts.components import Table
from pyecharts.faker import Faker
from aaa.utils import conn_mysql

alerts_from_mysql = conn_mysql.conn_mysql('select red_alerts,orange_alerts,yellow_alerts,blue_alerts from spider1170')
print(alerts_from_mysql)
red = []
orange = []
yellow = []
blue = []


def get_len(item, color, num):
    if item[num]:
        color.append(len(item[num].split('\n')))
    else:
        color.append('')

for item in alerts_from_mysql:
    print(item)
    get_len(item, red, 0)
    get_len(item, orange, 1)
    get_len(item, yellow, 2)
    get_len(item, blue, 3)

print(red,orange,yellow,blue)

def bar_datazoom_slider() -> Bar:
    Bar().set_colors(['red','orange','yellow','blue'])
    sql = 'SELECT red_alerts,orange_alerts,yellow_alerts,blue_alerts from spider1170'
    res = conn_mysql.conn_mysql(sql)
    print('bar res',res)
    c = (
        Bar()
        .add_xaxis(['娄底','长沙','邵阳','益阳'])
        .add_yaxis("红色预警",red,stack="stack1",itemstyle_opts=opts.ItemStyleOpts(color='#EE6666'))
        .add_yaxis("橙色预警", orange,stack="stack1",itemstyle_opts=opts.ItemStyleOpts(color='orange'))
        .add_yaxis("黄色预警", yellow,stack="stack1", itemstyle_opts=opts.ItemStyleOpts(color='yellow'))
        .add_yaxis("蓝色预警", blue, stack="stack1", itemstyle_opts=opts.ItemStyleOpts(color='#5470C6'))
        .reversal_axis()
        .set_series_opts(label_opts=opts.LabelOpts(is_show=True,position="inside",color= 'black'))
        .set_global_opts(title_opts=opts.TitleOpts(title="1170项目预警数量"),
                        xaxis_opts=opts.AxisOpts(name='预警级别',
                        axistick_opts=opts.AxisTickOpts(is_show=False)),
                        yaxis_opts=opts.AxisOpts(splitline_opts=opts.SplitLineOpts(is_show=True),name='地市'),
                         ))
    return c

def table_base() -> Table:
    table = Table()
    headers = ["地市", "红色预警", "橙色预警", "黄色预警","蓝色预警"]
    sql = 'SELECT * from spider1170'
    res = conn_mysql.conn_mysql(sql)
    ld,css,sys,yys = res[0],res[1],res[2],res[3]
    print('get_alerts res', ld,css,sys,yys)
    rows = [
        [ld[1], ld[2], ld[3],ld[4],ld[5]],
        [css[1], css[2], css[3], css[4], css[5]],
        [sys[1], sys[2], sys[3], sys[4],sys[5]],
        [yys[1], yys[2], yys[3], yys[4],yys[5]],
    ]
    table.add(headers, rows).set_global_opts(
        title_opts=opts.ComponentTitleOpts(title="1170项目预警分布")
    )
    return table


def page_draggable_layout():
    page = Page(layout=Page.DraggablePageLayout)
    page.add(
        bar_datazoom_slider(),
        table_base(),
    )
    page.render("page_draggable_layout.html")


if __name__ == "__main__":
    page_draggable_layout()
